import m_dlib.face_marks as fmarks
from PIL import Image


def crop_photo(path, target):
    path = path
    shape, d = fmarks.predictor_face(path)

    WIDTH_1IN = d.right()-d.left()
    HEIGHT_1IN = (d.right()-d.left()) * 1.4

    # 人像中心点
    X_CENTRE = d.left()+(d.right()-d.left()) / 2
    Y_CENTER = d.top()+(d.bottom()-d.top()) / 2

    im = Image.open(path)
    relativeSizeX = im.width / 1428.5
    relativeSizeY = im.height / 2000
    if d.left() < relativeSizeX * 400:
        raise Exception("人脸左侧空间不够")
    if d.top() < relativeSizeY * 200:
        raise Exception("人脸上侧空间不够")
    if im.width - d.right() < relativeSizeX * 400:
        raise Exception("人脸右侧空间不够")
    if im.height < Y_CENTER+HEIGHT_1IN:
        raise Exception("人脸下侧空间不够")
    im = im.crop((X_CENTRE-WIDTH_1IN, Y_CENTER-HEIGHT_1IN, X_CENTRE+WIDTH_1IN, Y_CENTER+HEIGHT_1IN))
    im.save(target)
